package com.opal.modules.essence.controller;

import com.mchange.v1.io.InputStreamUtils;
import com.opal.domain.ReturnMessageData;
import com.opal.modules.essence.service.StockInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;

@RequestMapping("/essence")
@Controller
public class StockInfoController {
    @Autowired
    private StockInfoService stockInfoService;

    /**
     * excel导入物料
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/upload")
    @ResponseBody
    public ReturnMessageData uploadExcel(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        MultipartFile file = multipartRequest.getFile("filename");
        if (file.isEmpty()) {
            return new ReturnMessageData(500,"请先选择excel备料文件上传！");
        }
        InputStream inputStream = file.getInputStream();
        ReturnMessageData r = stockInfoService.getBankListByExcel(inputStream, file.getOriginalFilename());
        inputStream.close();

        return r;
    }

    /**
     * 下载模版
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/downloadTemplate",produces="application/octet-stream")
    @ResponseBody
    public byte[] downloadTemplate(HttpServletResponse response) throws Exception {
        //获取服务器中所在文件
        //String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String filename="stockinfo.xls";
        InputStream rs = Thread.currentThread().getContextClassLoader().getResourceAsStream("static/templates/stocklnfo/"+filename);
//        File  f = new File(path);
//        byte[] bytes = FileUtils.getBytes(f);
//        int i = path.lastIndexOf("/");
//        String filename=path.substring(i+1,path.length());
        byte[] bytes = InputStreamUtils.getBytes(rs);

        String encode = URLEncoder.encode(filename, "utf-8");
        //设置响应头
       // response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename="+encode);
        //response.getOutputStream().write(resourceAsStream);
        return bytes;
    }

    @RequestMapping("{path}")
    public String skip(@PathVariable("path") String path){
        return "essence/"+path;
    }
}
